﻿namespace DeXrm.Win.Trace
{
    using System.Drawing;
    using DeXrm.Clas.Trace;
    using Properties;
    using Clas.Trace.Object;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Windows.Forms;
    
    public partial class DeXrmTrace : Form
    {
        #region Varibales

        List<DeXrmObjectLog> _lstObject = new List<DeXrmObjectLog>();
        static String sUrl;
        #endregion

        public DeXrmTrace()
        {
            InitializeComponent();

            #region Eventos
            btnOpenFile.Click += BtnOpenFileClick;
            btnTrace.Click += btnTrace_Click;
            dgvRegistro.CellFormatting += DgvRegistroCellFormatting;
            dgvRegistro.Click += DgvRegistroClick;
            dgvRegistro.SelectionChanged += DgvRegistroClick;
            btnFindError.Click += BtnFindErrorClick;
            #endregion

            #region Valores por defecto

            //this.txtWarTraceEnabled.Visible = false;
            this.filtroToolStripMenuItem.Enabled = false;

            #endregion
        }

        #region Eventos

        private void BtnFindErrorClick(object sender, EventArgs e)
        {
            if(String.IsNullOrEmpty(sUrl))
                sUrl = String.Format("{0}\\{1}",
                DeXrmCrmRegedit.GetValueString("CRM_Server_InstallDir", "Software\\Microsoft\\MSCRM")
                , "Trace");

            var frmShowFile = new DeXrmTraceShowFiles();
            frmShowFile.FindFile(sUrl);
            frmShowFile.ShowDialog();
        }

        private void btnTrace_Click(object sender, EventArgs e)
        {
            var deXrmFolder = new DeXrmTraceSett();
            deXrmFolder.ShowDialog();
        }

        private void BtnOpenFileClick(object sender, EventArgs e)
        {
            OpenFile = new OpenFileDialog
                           {
                               Filter = Resources.FileType,
                               InitialDirectory = DeXrmCrmRegedit.GetValueString("CRM_Server_InstallDir","Software\\Microsoft\\MSCRM")
                               
                           };
            if (OpenFile.ShowDialog() == DialogResult.OK)
                if (OpenFile.FileName != null)
                {
                    FillGridView(OpenFile.FileName);
                    dgvRegistro.Columns[0].Visible = true;
                    dgvRegistro.Columns[10].Visible = false;
                }
        }

        private void DgvRegistroCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            dgvRegistro.Columns[9].Visible = false;
            if (dgvRegistro.Columns[e.ColumnIndex].Name != "Level") return;
            var row = dgvRegistro.Rows[e.RowIndex];
            if (e.Value != null)
                switch (e.Value.ToString())
                {
                    case "Error":
                        row.DefaultCellStyle.BackColor = Color.Firebrick;
                        break;
                    case "Info":
                        row.DefaultCellStyle.BackColor = Color.Gainsboro;
                        break;
                    case "Warning":
                    case "Verbose":
                        row.DefaultCellStyle.BackColor = Color.Khaki;
                        break;
                }
        }

        private void DgvRegistroClick(object sender, EventArgs e)
        {
            if (dgvRegistro.CurrentRow == null) return;
            var dataGridViewCell = dgvRegistro.CurrentRow.Cells[9];
            txtDetail.Text = dataGridViewCell.Value.ToString();
        }

        private void DeXrmTraceLoad(object sender, EventArgs e)
        {
            if (DeXrmCrmRegedit.GetValueOption("TraceEnabled", "Software\\Microsoft\\MSCRM") != true) return;
            errorProv.SetError(txtWarTraceEnabled, "Verifique los permisos de trace");
            txtWarTraceEnabled.Visible = true;
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">Ruta del Log</param>
        public void FillGridView(String path)
        {
            var fileInfo = new FileInfo(path);
            if (!fileInfo.Exists)
                return;

            DeXrmObjectLog crmLogEntry2 = null;
            var crmLogEntry1 = new DeXrmObjectLog();

            using (var fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                FillGrid(fileStream, crmLogEntry1, crmLogEntry2);
            }
        }

        private void FillGrid(Stream fileStream, DeXrmObjectLog crmLogEntry1, DeXrmObjectLog crmLogEntry2)
        {
            dgvRegistro.DataSource = Util.ConvertFile(fileStream, crmLogEntry1, crmLogEntry2); 
        }

        

        #region Métodos

        public void VerificaEnabledTrace(bool bTrace, String sPath)
        {
            sUrl = sPath;
            if (bTrace == false) return;
            errorProv.SetError(txtWarTraceEnabled, "Verifique los permisos de trace");
            txtWarTraceEnabled.Visible = true;
        }

        #endregion


    }
}